// pages/message/message.js
var app = getApp();
const util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    msgLeave: [],
    msgReply: [],
    // 定义一个评论对象
    content: '',
    placeholder: '留言吧...',
    focus: false,
    now_reply: 0,
    now_author: '',
    now_reply_type: 0,
    now_answer: 0,
    showIcon: true,
    height: '',
    tabBarHeight: ''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.request({ // 发送请求
      url: 'https://nottoday.club/index.php/api/Guestbook/getAllGuestbook', // 请求的url
      method: 'GET',
      header: { 'cookie': wx.getStorageSync("sessionid") },
      success: (res) => {  // 请求成功的回调函数
        // console.log(res.data.data)  
        // 请求的成功的数据对象，注意是封装后的对象
        // 将所有返回信息转换为留言和评论放入不同的列表
        let msgLeave = []
        let msgReply = []
        res.data.data.forEach(element => {
          if (element.answer === 0) {
            element.children = []
            msgLeave.push(element)
          } else {
            msgReply.push(element)
          }
        })
        msgReply = msgReply.reverse()
        // console.log(msgLeave)
        msgLeave.forEach(element => {
          msgReply.forEach(element1 => {
            if (element1.answer === element.id) {
              element1.toAuthor = element.author
              element.children.push(element1)
            }
          })
        })
        this.setData({
          msgLeave: msgLeave
        })
      }
    })
  },
  // 回复留言
  replyComment: function (e) {
    this.setData({
      now_reply: e.currentTarget.dataset.cid,
      now_author: e.currentTarget.dataset.name,
      now_reply_type: e.currentTarget.dataset.type,
      now_answer: e.currentTarget.dataset.pid,
      focus: true,
      showIcon: false,
      placeholder: '回复' + e.currentTarget.dataset.name + ":"
    })
  },
  // 实时获取input框中的co内容,并讲内容存到this.data中
  getCommentText: function (e) {
    var val = e.detail.value;
    this.setData({
      content: val
    })
  },
  // 获取键盘弹起时的高度
  inputFocus(e) {
    let systemInfo = wx.getSystemInfoSync()
    // let tabbarHeight = systemInfo.screenHeight - systemInfo.statusBarHeight - systemInfo.windowHeight
    // console.log(tabbarHeight)

    // px转换到rpx的比例
    let pxToRpxScale = 750 / systemInfo.windowWidth;
    console.log(pxToRpxScale)
    // 状态栏的高度
    let ktxStatusHeight = systemInfo.statusBarHeight * pxToRpxScale
    // 导航栏的高度
    let navigationHeight = 44 * pxToRpxScale
    // window的宽度
    let ktxWindowWidth = systemInfo.windowWidth * pxToRpxScale
    // window的高度
    let ktxWindowHeight = systemInfo.windowHeight * pxToRpxScale
    // 屏幕的高度
    let ktxScreentHeight = systemInfo.screenHeight * pxToRpxScale
    // 底部tabBar的高度
    let tabBarHeight = ktxScreentHeight - ktxStatusHeight - navigationHeight - ktxWindowHeight
    console.log(tabBarHeight)
    console.log(e, '键盘弹起')
    this.setData({
      height: e.detail.height * pxToRpxScale  - tabBarHeight,
    })
    console.log(this.data.height)
  },
  // 是否显示icon
  setIcon: function (e) {
    this.setData({
      showIcon: false,
      focus: true,
      placeholder: '留言吧...',
      now_reply: 0,
      now_author: '',
      now_reply_type: 0,
      now_answer: 0
    })
  },
  hideInput: function (e) {
    this.setData({
      focus: false,
      showIcon: true,
      // content: '',
      height: 0
    });
  },
  // 发送按钮
  sendComment: function () { 
    // console.log('发送之前的data信息')
    // console.log(this.data)
    var that = this
    var UserInfo = app.globalData.UserInfo
    if (this.data.content != '') {
      var msgLeave = that.data.msgLeave  //获取data中的评论列表
      var msgReply = that.data.msgReply  //获取data中的回复列表
      // console.log(that.data.now_answer)
      var comment_detail = {}
      comment_detail.id = msgLeave.length > msgReply.length ? msgLeave.length + 1 : msgReply.length + 1
      comment_detail.authorid = UserInfo.authorId //获取用户登陆的id
      comment_detail.level = UserInfo.nowtext // 获取用户的权限id
      comment_detail.authorlevel = UserInfo.nowtext // 获取用户的权限id
      // comment_detail.comment_user_avatar = comment_user_avatar
      comment_detail.content = that.data.content  //获取当前的评论信息
      comment_detail.create_time = util.formatTime(new Date())  //格式化时间戳
      comment_detail.answer = that.data.now_answer //获取回复的评论id
      comment_detail.author = UserInfo.curName  //用户昵称
      comment_detail.toAuthor = that.data.now_author
      if (comment_detail.answer > 0) {
        msgReply.push(comment_detail) // push() 方法可向数组的末尾添加一个或多个元素，并返回新的长度。
        msgLeave.forEach(element => {
          if (element.id === comment_detail.answer) {
            element.children.push(comment_detail)
          }
        })
      } else {
        msgLeave.unshift(comment_detail) // unshift() 方法可向数组的开头添加一个或更多元素，并返回新的长度。
      }
      that.setData({
        content: null,
        now_reply: 0,
        now_author: null,
        now_reply_type: 0,
        now_answer: 0,
        placeholder: '留言吧...',
        msgLeave,
        msgReply
      }, () => {
        // 这里写访问后台插入数据库的代码
        // console.log('这里写你访问后台插入数据库的代码')
        // console.log(comment_detail)
        wx.request({
          url: 'https://nottoday.club/index.php/api/Guestbook/addGuestbook', 
          method: 'POST',
          header: { 'cookie': wx.getStorageSync("sessionid") },
          data: {
            author: comment_detail.author,
            authorid: comment_detail.authorid,
            authorlevel: comment_detail.authorlevel,
            answer: comment_detail.answer,
            content: comment_detail.content,
            level: comment_detail.level
          },
          header: {
            'content-type': 'application/json' // 默认值
          },
          success(res) {
            wx.showToast({
              title: '留言成功！',
              icon: 'none',
              duration: 2500 // 持续的时间
            })
          }
        })
      })
    } else {
      wx.showToast({
        title: '信息不能为空！',
        icon: 'none',
        duration: 2500 // 持续的时间
      })
    }
  },
  /*
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.onLoad()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})